package com.purong.purong.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.purong.purong.Contant;
import com.purong.purong.PuRongApp;
import com.purong.purong.R;
import com.purong.purong.activity.CreditDetialActivity;
import com.purong.purong.activity.CreditSearchActivity;
import com.purong.purong.activity.LoginActivity;
import com.purong.purong.activity.MainActivity;
import com.purong.purong.activity.ScheduleQueryActivity;
import com.purong.purong.activity.WebActivity;
import com.purong.purong.adapter.BankGridAdapter;
import com.purong.purong.adapter.CreditThemedAdapter;
import com.purong.purong.adapter.HomeCreditcardAdapter;
import com.purong.purong.bean.ADInfo;
import com.purong.purong.bean.AdListBean;
import com.purong.purong.bean.BankBean;
import com.purong.purong.bean.CreditBankListBean;
import com.purong.purong.bean.CreditCardBean;
import com.purong.purong.bean.CreditRecommBean;
import com.purong.purong.bean.CreditTagListBean;
import com.purong.purong.bean.CreditTagListBean.CreditTagBean;
import com.purong.purong.bean.SearchValueBean;
import com.purong.purong.util.CommonUtil;
import com.purong.purong.util.SharePreUtil;
import com.purong.purong.widget.CustomCycleViewPager;
import com.purong.purong.widget.ExtGridLayoutManager;
import com.purong.purong.widget.FullyLinearLayoutManager;
import com.purong.purong.widget.GradationScrollView;
import com.yao.sdk.glide.GlideUtil;
import com.yao.sdk.net.ResponseInfo;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wenjiezeng on 2017/9/20.
 */
public class CreditCardFragment extends BaseFragment implements GradationScrollView.ScrollViewListener{
    private GradationScrollView mScrollView;
    private RelativeLayout titleBar;
    private LinearLayout indicatorLay,topLay,centerIndicaLay,themeTitle,hotTitle;
    private ImageView statusBar,centerCbBg;
    private CustomCycleViewPager mLikeViewPager;
    private List<View> likeViews = new ArrayList<View>();
    private ArrayList<BankBean> mBankList = new ArrayList<BankBean>();
    private ImageView[] indicators,centerIndicators;
    private String cityId="";
    private ConvenientBanner centerCb;
    private RecyclerView mThemeRecycler,mCreditRecycler;
    private HomeCreditcardAdapter mAdapter;
    private CreditThemedAdapter mThemeAdapter;
    private List<CreditCardBean> creditList=new ArrayList<>();
    private ArrayList<CreditTagBean> mThemeList = new ArrayList<CreditTagBean>();
    private int titleBarRange;
    private boolean getBankSuc,getAdSuc,gethotSuc,getThemeSuc;
    @Override
    public void onResume() {
        super.onResume();
        if (!cityId.equals(SharePreUtil.getInstance(getActivity()).getLoactionAreaId())){
            cityId=SharePreUtil.getInstance(getActivity()).getLoactionAreaId();
            getBankList();
            getAd();
            getRecommCredit();
            getEssenceCredit();
        }else {
            if (!getBankSuc)
                getBankList();
            if (!getAdSuc)
                getAd();
            if (!gethotSuc)
                getRecommCredit();
            if (!getThemeSuc)
                getEssenceCredit();
        }



    }

    public void initView(View v){
        titleBarRange=CommonUtil.dip2px(getActivity(),100);
        indicatorLay=(LinearLayout)v.findViewById(R.id.indicator_lay);
        centerIndicaLay = (LinearLayout) v.findViewById(R.id.center_indicator_lay);
        topLay=(LinearLayout)v.findViewById(R.id.top_lay);
        themeTitle=(LinearLayout)v.findViewById(R.id.theme_title);
        hotTitle=(LinearLayout)v.findViewById(R.id.hot_title);
        titleBar=(RelativeLayout)v.findViewById(R.id.title_bar);
        statusBar = (ImageView) v.findViewById(R.id.status_bar);
        centerCbBg=(ImageView)v.findViewById(R.id.center_cb_bg);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT){
            statusBar.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0));
            topLay.setPadding(0,CommonUtil.dip2px(getActivity(),85)-CommonUtil.getStatusBarHeight(getActivity()),0,CommonUtil.dip2px(getActivity(),15));
        }else {
            statusBar.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, CommonUtil.getStatusBarHeight(getActivity())));
            topLay.setPadding(0,CommonUtil.dip2px(getActivity(),85),0,CommonUtil.dip2px(getActivity(),15));
        }
        mScrollView = (GradationScrollView) v.findViewById(R.id.scrollview);
        mScrollView.setScrollViewListener(this);
        mLikeViewPager = (CustomCycleViewPager) getActivity().getFragmentManager()
                .findFragmentById(R.id.fragment_like_viewpager);
        centerCb=(ConvenientBanner)v.findViewById(R.id.center_cb);
        int centerHeight = (int) (CommonUtil.getScreenWidth(getActivity()) * 0.24);
        RelativeLayout.LayoutParams centerLp=new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, centerHeight);
        centerCb.setLayoutParams(centerLp);
        centerCbBg.setLayoutParams(centerLp);
        mThemeRecycler=(RecyclerView)v.findViewById(R.id.theme_recycler_view);
        mThemeAdapter = new CreditThemedAdapter(getActivity());
        mThemeAdapter.setOnCreditThemedListener(new CreditThemedAdapter.OnCreditThemedListener() {
            @Override
            public void onThemed(CreditTagBean tag) {
                ArrayList<SearchValueBean> list=new ArrayList<SearchValueBean>();
                SearchValueBean bean=new SearchValueBean();
                bean.setItem(tag.getCredit_tag_id());
                bean.setParentFiled("credit_tag");
                list.add(bean);
                Intent intent=new Intent(getActivity(), CreditSearchActivity.class);
                intent.putExtra("BANK_LIST",mBankList);
                intent.putExtra("CHOSE_MORE",list);
                startActivity(intent);

            }
        });
        mThemeAdapter.setData(mThemeList);
        mThemeRecycler.setLayoutManager(new ExtGridLayoutManager(getActivity(),2));
        mThemeRecycler.setAdapter(mThemeAdapter);
        mCreditRecycler=(RecyclerView)v.findViewById(R.id.credit_recycler_view);
        mAdapter = new HomeCreditcardAdapter(getActivity());
        mAdapter.setOnCreditClickListener(new HomeCreditcardAdapter.OnCreditClickListener() {
            @Override
            public void onCreditClick(CreditCardBean card) {
                Intent intent=new Intent(getActivity(), CreditDetialActivity.class);
                intent.putExtra("CREDIT",card);
                startActivity(intent);
            }
        });
        mAdapter.setData(creditList);
        mCreditRecycler.setLayoutManager(new FullyLinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        mCreditRecycler.setAdapter(mAdapter);
        v.findViewById(R.id.query_schedule).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent;
                if (PuRongApp.getLoginInfo(getActivity())!=null){
                    intent=new Intent(getActivity(), ScheduleQueryActivity.class);
                    startActivity(intent);
                }else {
                    intent=new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                }

            }
        });
        v.findViewById(R.id.credit_article).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((MainActivity)getActivity()).jumpArticleCredit();
            }
        });
        v.findViewById(R.id.all_bank).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getActivity(), CreditSearchActivity.class);
                intent.putExtra("BANK_LIST",mBankList);
                startActivity(intent);
            }
        });
        v.findViewById(R.id.more_credit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getActivity(), CreditSearchActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    public void initData() {

    }

    @Override
    public int getRootViewId() {
        return R.layout.fragment_creditcard;
    }

    private void getRecommCredit(){
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("recommend_location","2");
        params.put("city_id", SharePreUtil.getInstance(getActivity()).getLoactionAreaId());
        params.put("province_id", SharePreUtil.getInstance(getActivity()).getLoactionParentId());
        gethotSuc=requestNoToast(Contant.CREDIT_RECOMMEND, params, true, false);
    }
    private void getEssenceCredit(){
        Map<String, String> params = new LinkedHashMap<String, String>();
        getThemeSuc=requestNoToast(Contant.CREDIT_TAG, params, true, false);
    }
    private void getAd(){
        Map<String, String> topParams = new LinkedHashMap<String, String>();
        topParams.put("location_code","CreditMiddle");
        topParams.put("city_id",SharePreUtil.getInstance(getActivity()).getLoactionAreaId());
        getAdSuc=requestNoToast(Contant.AD_IMG, topParams, true, false);
    }
    private void setAdInfo(final AdListBean adBean) {
        centerCbBg.setVisibility(View.GONE);
        centerCb.setPages(new CBViewHolderCreator<ImageViewHolder>() {
            @Override
            public ImageViewHolder createHolder() {
                return new ImageViewHolder(GlideUtil.HROIZONTAL);
            }
        }, adBean.getAd_list());
        if (adBean.getAd_list().size()>1){
            initCenterIndicator(adBean);
            centerCb.startTurning(5000);
            centerCb.setCanLoop(true);
        }else {
            centerCb.setCanLoop(false);
        }

        centerCb.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                setCenterIndicator(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        centerCb.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (adBean.getAd_list().get(position).getAd_goto_url()!=null&&
                        (adBean.getAd_list().get(position).getAd_goto_url().startsWith("http")||adBean.getAd_list().get(position).getAd_goto_url().startsWith("HTTP"))){
                    Intent intent=new Intent(getActivity(),WebActivity.class);
                    intent.putExtra("TITLE", adBean.getAd_list().get(position).getAd_name());
                    intent.putExtra("URL", adBean.getAd_list().get(position).getAd_goto_url());
                    intent.putExtra("TITLEBAR", true);
                    startActivity(intent);
                }
            }
        });


    }
    private void initCenterIndicator(AdListBean mAdBean) {
        centerIndicaLay.removeAllViews();
        if (mAdBean != null && mAdBean.getAd_list() != null&&mAdBean.getAd_list().size()>1) {
            centerIndicators = new ImageView[mAdBean.getAd_list().size()];
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(CommonUtil.dip2px(getActivity(), 10), CommonUtil.dip2px(getActivity(), 3));
            lp.setMargins(CommonUtil.dip2px(getActivity(), 3), 0, CommonUtil.dip2px(getActivity(), 3), 0);
            for (int i = 0; i < mAdBean.getAd_list().size(); i++) {
                ImageView indicatorImg = new ImageView(getActivity());
                if (i == 0) {
                    indicatorImg.setImageResource(R.drawable.lunbodian_sel);
                } else {
                    indicatorImg.setImageResource(R.drawable.lunbodian_nor);

                }
                indicatorImg.setLayoutParams(lp);
                centerIndicaLay.addView(indicatorImg);
                centerIndicators[i] = indicatorImg;
            }

        }
    }
    private void setCenterIndicator(int selectedPosition) {
        if (centerIndicators == null)
            return;
        for (int i = 0; i < centerIndicators.length; i++) {
            centerIndicators[i]
                    .setImageResource(R.drawable.lunbodian_nor);
        }
        if (centerIndicators.length > selectedPosition)
            centerIndicators[selectedPosition]
                    .setImageResource(R.drawable.lunbodian_sel);
    }
    private void getBankList(){
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("city_id",SharePreUtil.getInstance(getActivity()).getLoactionAreaId());
        getBankSuc=requestNoToast(Contant.BANK, params, true, false);
    }

    @Override
    public void onResponse(ResponseInfo responseInfo) {
        if (hasDestroy())
            return;
        super.onResponse(responseInfo);
        if (responseInfo.url.equals(Contant.BANK)){
            if (responseInfo.isRequestOk){
                try{
                    CreditBankListBean bankListBean=JSON.parseObject(responseInfo.content,CreditBankListBean.class);
                    if (bankListBean!=null&&bankListBean.getBank_list()!=null){
                        Log.e("zwj","......bank");
                        mBankList.clear();
                        mBankList.addAll(bankListBean.getBank_list());
                        initializeLikes();
                        getBankSuc=true;
                    }else {
                        getBankSuc=false;
                    }
                }catch (Exception e){
                    getBankSuc=false;
                }
            }else {
                getBankSuc=false;
            }
        }else if (responseInfo.url.equals(Contant.CREDIT_RECOMMEND)){
            if (responseInfo.isRequestOk){
                try {
                    CreditRecommBean bean=JSON.parseObject(responseInfo.content,CreditRecommBean.class);
                    if (bean!=null&&bean.getCredit_recommend_list()!=null){
                        creditList.clear();
                        creditList.addAll(bean.getCredit_recommend_list());
                        mAdapter.notifyDataSetChanged();
                        if (creditList.size()!=0){
                            hotTitle.setVisibility(View.VISIBLE);
                        }else {
                            hotTitle.setVisibility(View.GONE);
                        }
                        gethotSuc=true;
                    }else {
                        gethotSuc=false;
                    }

                }catch (Exception e){
                    gethotSuc=false;
                }
            }else {
                gethotSuc=false;
            }
        }else if (responseInfo.url.equals(Contant.CREDIT_TAG)){
            if (responseInfo.isRequestOk){
                try {
                    CreditTagListBean bean=JSON.parseObject(responseInfo.content,CreditTagListBean.class);
                    if (bean!=null&&bean.getTag_list()!=null){
                        mThemeList.clear();
                        mThemeList.addAll(bean.getTag_list());
                        mThemeAdapter.notifyDataSetChanged();
                        if (mThemeList.size()!=0){
                            themeTitle.setVisibility(View.VISIBLE);
                        }else {
                            themeTitle.setVisibility(View.GONE);
                        }
                        getThemeSuc=true;
                    }else {
                        getThemeSuc=false;
                    }
                }catch (Exception e){
                    getThemeSuc=false;
                }
            }else {
                getThemeSuc=false;
            }
        }else if (responseInfo.url.equals(Contant.AD_IMG)){
            if (responseInfo.isRequestOk){
                try{
                    AdListBean bean=JSON.parseObject(responseInfo.content,AdListBean.class);
                    if (bean!=null&&bean.getAd_list()!=null&&bean.getAd_list().size()>0){
                        setAdInfo(bean);
                        getAdSuc=true;
                    }else {
                        getAdSuc=false;
                    }

                }catch (Exception e){
                    getAdSuc=false;
                }
            }else {
                getAdSuc=false;
            }
        }
    }


    private void initializeLikes() {


        likeViews.clear();
        int count = 0;
        if (mBankList != null) {
            count = mBankList.size() / 8;
            if (mBankList.size() % 8 > 0) {
                count++;
            }
            initBankIndicator(count);
            if (count == 1) {
                likeViews.add(getImageView(getActivity(), mBankList, new BankGridAdapter.OnBankClickListener() {
                    @Override
                    public void onClick(BankBean bean) {
                        Intent intent=new Intent(getActivity(), CreditSearchActivity.class);
                        intent.putExtra("BANK_LIST",mBankList);
                        intent.putExtra("CHOSE_BANK",bean);
                        startActivity(intent);

                    }
                }));
            } else {
                // 将最后一个ImageView添加进来
                ArrayList<BankBean> mLastBankList = new ArrayList<BankBean>();
                for (int i = 0; i < mBankList.size(); i++) {
                    if (i >= 8 * (count - 1)) {
                        BankBean bean = mBankList.get(i);
                        if (bean != null) {
                            mLastBankList.add(bean);
                        }
                    }
                }
                likeViews.add(getImageView(getActivity(), mLastBankList, null));
                for (int i = 0; i < count; i++) {
                    ArrayList<BankBean> mMiddleBankList = new ArrayList<BankBean>();
                    for (int j = 0; j < 8; j++) {
                        if ((j + i * 8) < mBankList.size()) {
                            BankBean bean = mBankList.get(j + i * 8);
                            if (bean != null) {
                                mMiddleBankList.add(bean);
                            }
                        }
                    }
                    likeViews.add(getImageView(getActivity(), mMiddleBankList, new BankGridAdapter.OnBankClickListener() {
                        @Override
                        public void onClick(BankBean bean) {
                            Intent intent=new Intent(getActivity(), CreditSearchActivity.class);
                            intent.putExtra("BANK_LIST",mBankList);
                            intent.putExtra("CHOSE_BANK",bean);
                            startActivity(intent);
                        }
                    }));
                }
                ArrayList<BankBean> mFirstBankList = new ArrayList<BankBean>();
                for (int i = 0; i < mBankList.size(); i++) {
                    if (i < 8) {
                        BankBean bean = mBankList.get(i);
                        if (bean != null) {
                            mFirstBankList.add(bean);
                        }
                    }
                }
                // 将第一个ImageView添加进来
                likeViews.add(getImageView(getActivity(), mFirstBankList, null));
            }

            if (count == 1) {
                mLikeViewPager.setCycle(false);

            } else {
                mLikeViewPager.setCycle(true);
            }
            mLikeViewPager.ShowIndicator(false);
            // 在加载数据前设置是否循环
            //设置轮播
            mLikeViewPager.setWheel(false);
            mLikeViewPager.setData(likeViews, mBankList);
            mLikeViewPager.setOnPageSelectListener(new CustomCycleViewPager.OnPageSelectListener() {
                @Override
                public void onSelect(int position) {
                    setBankIndicator(position);
                }
            });
        }
        // 设置循环，在调用setData方法前调用


    }
    private  View getImageView(Context context, List<BankBean> infos,BankGridAdapter.OnBankClickListener listener) {
        View layout = LayoutInflater.from(context).inflate(
                R.layout.bank_gridview_page, null);
        GridView gv = (GridView) layout.findViewById(R.id.bank_gridView);
        BankGridAdapter mBankGridAdapter = new BankGridAdapter(context, infos);
        gv.setAdapter(mBankGridAdapter);
        mBankGridAdapter.setOnBankClickListener(listener);
        return layout;
    }
    private void initBankIndicator(int size) {

        if (size>0) {
            indicatorLay.removeAllViews();
            indicators = new ImageView[size];
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(CommonUtil.dip2px(getActivity(), 12), CommonUtil.dip2px(getActivity(), 3));
            lp.setMargins(CommonUtil.dip2px(getActivity(), 3), 0, CommonUtil.dip2px(getActivity(), 3), 0);
            for (int i = 0; i < size; i++) {
                ImageView indicatorImg = new ImageView(getActivity());
                if (i == 0) {
                    indicatorImg.setImageResource(R.drawable.cart_lunbodian_sel);
                } else {
                    indicatorImg.setImageResource(R.drawable.cart_lunbodian_nor);

                }
                indicatorImg.setLayoutParams(lp);
                indicatorLay.addView(indicatorImg);
                indicators[i] = indicatorImg;
            }

        }
    }
    private void setBankIndicator(int selectedPosition) {
        if (indicators == null)
            return;
        for (int i = 0; i < indicators.length; i++) {
            indicators[i]
                    .setImageResource(R.drawable.cart_lunbodian_nor);
        }
        if (indicators.length > selectedPosition)
            indicators[selectedPosition]
                    .setImageResource(R.drawable.cart_lunbodian_sel);
    }
    @Override
    public void onScrollChanged(GradationScrollView scrollView, int x, int y, int oldx, int oldy) {
        if (y <= 0) {   //设置标题的背景颜色
            titleBar.setBackgroundColor(Color.argb((int) 0, 144, 151, 166));
            statusBar.setBackgroundColor(Color.argb((int) 0, 144, 151, 166));
        } else if (y > 0 && y <= titleBarRange) { //滑动距离小于banner图的高度时，设置背景和字体颜色颜色透明度渐变
            float scale = (float) y / titleBarRange;
            float alpha = (255 * scale);
            titleBar.setBackgroundColor(Color.argb((int) alpha, 71, 158, 248));
            statusBar.setBackgroundColor(Color.argb((int) alpha, 71, 158, 248));
        } else {    //滑动到banner下面设置普通颜色
            titleBar.setBackgroundColor(Color.argb((int) 255, 71, 158, 248));
            statusBar.setBackgroundColor(Color.argb((int) 255, 71, 158, 248));
        }
    }

    public class ImageViewHolder implements Holder<ADInfo> {
        private ImageView imageView;
        private int placeHolderType;

        public ImageViewHolder(int placeHolderType) {
            this.placeHolderType=placeHolderType;
        }

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, ADInfo data) {
            GlideUtil.getInstance().load(getActivity(), data.getAd_photo_url(), imageView, true,placeHolderType);
        }
    }
}
